#! /bin/sh

set -ex

srcdir="$(dirname "$0")"
test -z "$srcdir" && srcdir=.

cd "$srcdir"

clone_repo_commit() {
    if test -d "$2/.git"; then
        git -C "$2" reset --hard
        git -C "$2" clean -fd
        if ! git -C "$2" checkout $3; then
            rm -rf "$2"
        fi
    else
        if test -d "$2"; then
            set +x
            echo "error: '$2' is not a Git repository"
            exit 1
        fi
    fi
    if ! test -d "$2"; then
        git clone $1 "$2"
        if ! git -C "$2" checkout $3; then
            rm -rf "$2"
            exit 1
        fi
    fi
}

download_by_hash() {
    DOWNLOAD_COMMAND="curl -Lo"
    if ! command -v "${DOWNLOAD_COMMAND%% *}" >/dev/null 2>&1; then
        DOWNLOAD_COMMAND="wget -O"
        if ! command -v "${DOWNLOAD_COMMAND%% *}" >/dev/null 2>&1; then
            set +x
            echo "error: Neither curl nor wget found"
            exit 1
        fi
    fi
    SHA256_COMMAND="sha256sum"
    if ! command -v "${SHA256_COMMAND%% *}" >/dev/null 2>&1; then
        SHA256_COMMAND="sha256"
        if ! command -v "${SHA256_COMMAND%% *}" >/dev/null 2>&1; then
            set +x
            echo "error: Cannot find sha256(sum) command"
            exit 1
        fi
    fi
    if ! test -f "$2" || ! $SHA256_COMMAND "$2" | grep $3 >/dev/null 2>&1; then
        rm -f "$2"
        mkdir -p "$2" && rm -rf "$2"
        $DOWNLOAD_COMMAND "$2" $1
        if ! $SHA256_COMMAND "$2" | grep $3 >/dev/null 2>&1; then
            set +x
            echo "error: Cannot download file '$2' by hash"
            echo "incorrect hash:"
            $SHA256_COMMAND "$2"
            rm -f "$2"
            exit 1
        fi
    fi
}

clone_repo_commit \
    https://codeberg.org/osdev/freestnd-c-hdrs-0bsd.git \
    freestnd-c-hdrs \
    a87c192f3eb66b0806740dc67325f9ad23fc2d0b

clone_repo_commit \
    https://codeberg.org/osdev/cc-runtime.git \
    cc-runtime \
    576a01179f3298a4795b92f42c088f9f8800b56b

# 1.0.2
clone_repo_commit \
    https://codeberg.org/mintsuki/flanterm.git \
    c/flanterm \
    9d0f67b89db1d83236f9ac291339248ba3d5f479

download_by_hash \
    https://github.com/charlesnicholson/nanoprintf/raw/0281ccf0b4105b194d5afb2cbb3cf308b9129d3a/nanoprintf.h \
    c/nanoprintf_orig.h \
    cb4f3b6fdb061c204fc641a3fd950d89daae1097bb1585f881cff056f775f6f1
sed '/NPF_WRITEBACK(LONG_DOUBLE/d' c/nanoprintf_orig.h >c/nanoprintf.h

# 2.0.0
clone_repo_commit \
    https://github.com/uACPI/uACPI.git \
    uacpi-repository \
    4ab3a78006a930e2cda5a92f33fc84e1ec6b4a3d
rm -rf c/uacpi
mkdir -p c/uacpi
cp -rp uacpi-repository/include/uacpi/* c/uacpi/
cp -rp uacpi-repository/source/* c/uacpi/
